package cn.zebra.dev.mall.module.orders.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.mall.module.orders.dto.BarterDTO;
import cn.zebra.dev.mall.module.orders.vo.BarterStateVO;
import cn.zebra.dev.mall.module.orders.vo.ShopBarterVO;
import cn.zebra.dev.mall.module.orders.vo.UserBarterVO;
import cn.zebra.dev.member.module.login.service.SecurityMemberService;
import cn.zebra.dev.member.module.member.entity.MemberEntity;
import cn.zebra.dev.member.module.member.service.MemberService;
import cn.zebra.dev.order.module.item.entity.OrdersItemEntity;
import cn.zebra.dev.order.module.item.service.OrdersItemService;
import cn.zebra.dev.other.module.ordersBarter.entity.OrdersBarterEntity;
import cn.zebra.dev.other.module.ordersBarter.service.OrdersBarterService;
import cn.zebra.dev.other.module.shopAfter.entity.ShopAfterEntity;
import cn.zebra.dev.other.module.shopAfter.service.ShopAfterService;
import cn.zebra.dev.product.module.collect.entity.MemberProductCollectEntity;
import cn.zebra.dev.product.module.product.entity.ProductEntity;
import cn.zebra.dev.product.module.sku.entity.ProductSkuEntity;
import cn.zebra.dev.product.module.sku.service.ProductSkuService;
import cn.zebra.dev.shop.module.shop.entity.ShopEntity;
import cn.zebra.dev.shop.module.shop.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author feifeijunxin
 * @Date 2020/5/8 17:15
 * @Version 1.0
 */
@Api(tags = "订单换货")
@RestController
@RequestMapping("/orders/barter")
public class BarterController {

    @Autowired
    private OrdersBarterService ordersBarterService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopAfterService shopAfterService;
    @Autowired
    private OrdersItemService ordersItemService;
    @Autowired
    private ProductSkuService productSkuService;
    @Autowired
    private SecurityMemberService securityMemberService;


    @GetMapping("/userList")
    @ApiOperation("用户换货列表(可根据状态查询，如没有状态条件则默认查全部)")
    public Result<PageUtils<BarterDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "userId") Long  userId,
            @RequestParam(value = "state",required = false) Long state){
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("userId",userId);
        if(state != null){
            map.put("state",state);
        }
        System.out.println(map.get("state"));
        PageUtils<OrdersBarterEntity> pageUtils = ordersBarterService.findPageByUserId(map);
        PageUtils<BarterDTO> data = new PageUtils<>(pageUtils);
        List<OrdersBarterEntity> list =pageUtils.getList();
        if(list.size() > 0){
            List<BarterDTO> dtos = new ArrayList<>();
            List<Long> shopAfterIds = list.stream().map(OrdersBarterEntity::getShopAfterId).collect(Collectors.toList());
            List<ShopAfterEntity> shopAfterEntities=shopAfterService.findByIds(shopAfterIds);
            List<Long> ordersItemIds = shopAfterEntities.stream().map(ShopAfterEntity::getOrderItemId).collect(Collectors.toList());
            List<OrdersItemEntity> ordersItemEntities = ordersItemService.findByIds(ordersItemIds);
            List<Long> productSkuIds = list.stream().map(OrdersBarterEntity::getProductSkuId).collect(Collectors.toList());
            List<ProductSkuEntity> productSkuEntities = productSkuService.findByIds(productSkuIds);
            List<Long> memberIds = list.stream().map(OrdersBarterEntity::getUserId).collect(Collectors.toList());
            List<MemberEntity> memberEntities=memberService.findByIds(memberIds);
            List<Long> shopIds = list.stream().map(OrdersBarterEntity::getShopId).collect(Collectors.toList());
            List<ShopEntity> shopEntities = shopService.findByIds(shopIds);

            list.forEach(entity ->{
                BarterDTO dto = new BarterDTO();
                BeanUtils.copyProperties(entity,dto);
                Optional<MemberEntity> memberEntityOptional = memberEntities.stream().filter(memberEntity -> memberEntity.getId().equals(entity.getUserId())).findAny();
                if(memberEntityOptional.isPresent()){
                    MemberEntity memberEntity = memberEntityOptional.get();
                    dto.setUserName(memberEntity.getMemberName());
                }
                Optional<ShopEntity> shopEntityOptional = shopEntities.stream().filter(shopEntity -> shopEntity.getId().equals(entity.getShopId())).findAny();
                if(memberEntityOptional.isPresent()){
                    ShopEntity shopEntity = shopEntityOptional.get();
                    dto.setShopName(shopEntity.getShopName());

                }
                Optional<ShopAfterEntity> shopAfterEntityOptional = shopAfterEntities.stream().filter(shopAfterEntity -> shopAfterEntity.getId().equals(entity.getShopAfterId())).findAny();
                if(shopAfterEntityOptional.isPresent()){
                    ShopAfterEntity shopAfterEntity = shopAfterEntityOptional.get();
                    Optional<OrdersItemEntity> ordersItemsEntityOptional = ordersItemEntities.stream().filter(ordersItemEntity -> ordersItemEntity.getId().equals(shopAfterEntity.getOrderItemId())).findAny();
                    if(ordersItemsEntityOptional.isPresent()){
                        OrdersItemEntity ordersItemEntity = ordersItemsEntityOptional.get();
                        dto.setProductName(ordersItemEntity.getProductName());
                        dto.setProductImage(ordersItemEntity.getProductImage());
                    }
                }
                Optional<ProductSkuEntity> productSkuEntityOptional = productSkuEntities.stream().filter(productSkuEntity -> productSkuEntity.getId().equals(entity.getProductSkuId())).findAny();
                if(memberEntityOptional.isPresent()){
                    ProductSkuEntity productSkuEntity = productSkuEntityOptional.get();
                    dto.setProductSkuName(productSkuEntity.getProductSkuName());

                }

                dtos.add(dto);
            });
            data.setList(dtos);
        }
        return Result.success(data);
    }

    @GetMapping("/shopList")
    @ApiOperation("店铺换货列表(可根据状态查询，如没有状态条件则默认查全部)")
    public Result<PageUtils<BarterDTO>> shopList(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "shopId") Long  shopId,
            @RequestParam(value = "state",required = false) Long state){
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("shopId",shopId);
        map.put("state",state);
        PageUtils<OrdersBarterEntity> pageUtils = ordersBarterService.findPageByShopId(map);
        PageUtils<BarterDTO> data = new PageUtils<>(pageUtils);
        List<OrdersBarterEntity> list =pageUtils.getList();
        if(list.size() > 0){
            List<BarterDTO> dtos = new ArrayList<>();
            List<Long> shopAfterIds = list.stream().map(OrdersBarterEntity::getShopAfterId).collect(Collectors.toList());
            List<ShopAfterEntity> shopAfterEntities=shopAfterService.findByIds(shopAfterIds);
            List<Long> ordersItemIds = shopAfterEntities.stream().map(ShopAfterEntity::getOrderItemId).collect(Collectors.toList());
            List<OrdersItemEntity> ordersItemEntities = ordersItemService.findByIds(ordersItemIds);
            List<Long> productSkuIds = list.stream().map(OrdersBarterEntity::getProductSkuId).collect(Collectors.toList());
            List<ProductSkuEntity> productSkuEntities = productSkuService.findByIds(productSkuIds);
            List<Long> memberIds = list.stream().map(OrdersBarterEntity::getUserId).collect(Collectors.toList());
            List<MemberEntity> memberEntities=memberService.findByIds(memberIds);
            List<Long> shopIds = list.stream().map(OrdersBarterEntity::getShopId).collect(Collectors.toList());
            List<ShopEntity> shopEntities = shopService.findByIds(shopIds);

            list.forEach(entity ->{
                BarterDTO dto = new BarterDTO();
                BeanUtils.copyProperties(entity,dto);
                Optional<MemberEntity> memberEntityOptional = memberEntities.stream().filter(memberEntity -> memberEntity.getId().equals(entity.getUserId())).findAny();
                if(memberEntityOptional.isPresent()){
                    MemberEntity memberEntity = memberEntityOptional.get();
                    dto.setUserName(memberEntity.getMemberName());
                }
                Optional<ShopEntity> shopEntityOptional = shopEntities.stream().filter(shopEntity -> shopEntity.getId().equals(entity.getShopId())).findAny();
                if(memberEntityOptional.isPresent()){
                    ShopEntity shopEntity = shopEntityOptional.get();
                    dto.setShopName(shopEntity.getShopName());

                }
                Optional<ShopAfterEntity> shopAfterEntityOptional = shopAfterEntities.stream().filter(shopAfterEntity -> shopAfterEntity.getId().equals(entity.getShopAfterId())).findAny();
                if(shopAfterEntityOptional.isPresent()){
                    ShopAfterEntity shopAfterEntity = shopAfterEntityOptional.get();
                    Optional<OrdersItemEntity> ordersItemsEntityOptional = ordersItemEntities.stream().filter(ordersItemEntity -> ordersItemEntity.getId().equals(shopAfterEntity.getOrderItemId())).findAny();
                    if(ordersItemsEntityOptional.isPresent()){
                        OrdersItemEntity ordersItemEntity = ordersItemsEntityOptional.get();
                        dto.setProductName(ordersItemEntity.getProductName());
                        dto.setProductImage(ordersItemEntity.getProductImage());
                    }
                }
                Optional<ProductSkuEntity> productSkuEntityOptional = productSkuEntities.stream().filter(productSkuEntity -> productSkuEntity.getId().equals(entity.getProductSkuId())).findAny();
                if(memberEntityOptional.isPresent()){
                    ProductSkuEntity productSkuEntity = productSkuEntityOptional.get();
                    dto.setProductSkuName(productSkuEntity.getProductSkuName());

                }

                dtos.add(dto);
            });
            data.setList(dtos);
        }
        return Result.success(data);
    }

    @PostMapping("/save")
    @ApiOperation("客户发货")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@Valid @RequestBody UserBarterVO vo) {
        OrdersBarterEntity entity = new OrdersBarterEntity();
        BeanUtils.copyProperties(vo,entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.setState(0L);
        entity.setUserId(securityMemberService.getMemberId());
        ShopAfterEntity shopAfterEntity = shopAfterService.findById(entity.getShopAfterId());
        if(shopAfterEntity.getState() != 0L){
            return Result.error("商家还未同意处理，请耐心等待！！");
        }
        BeanUtils.copyProperties(shopAfterEntity,entity);
        entity.setId(null);
        if(ordersBarterService.save(entity)){
            return Result.success("操作成功！");
        }
        return Result.success("操作失败!");
    }

    @PostMapping("/update/{id}")
    @ApiOperation("商家发货")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@PathVariable Long id,@Valid @RequestBody ShopBarterVO vo) {
        OrdersBarterEntity entity = new OrdersBarterEntity();
        BeanUtils.copyProperties(vo,entity);
        OrdersBarterEntity ordersBarterEntity = ordersBarterService.findById(id);
        ShopAfterEntity shopAfterEntity = shopAfterService.findById(ordersBarterEntity.getShopAfterId());
        if(shopAfterEntity.getState() != 0L){
            return Result.error("商家还未同意处理，请同意后再试！！");
        }else if(ordersBarterEntity.getState() !=1L){
            return Result.error("商家还未签收，请耐心等待！！");
        }
        entity.setState(2L);
        if(ordersBarterService.update(entity,"id = {0}",id)){
            return Result.success("操作成功！");
        }
        return Result.success("操作失败!");
    }


    @PostMapping("/update/state/{id}")
    @ApiOperation("商家签收，用户签收！")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@PathVariable Long id, @Valid @RequestBody BarterStateVO vo) {
        OrdersBarterEntity entity = new OrdersBarterEntity();
        BeanUtils.copyProperties(vo,entity);
        if(ordersBarterService.update(entity,"id={0}",id)){
            return Result.success("操作成功!");
        }
        return Result.success("操作失败!");
    }



}
